package com.mobartisan.workinglunch.ui.fragment;

import android.app.Dialog;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.codetroopers.betterpickers.calendardatepicker.CalendarDatePickerDialogFragment;
import com.codetroopers.betterpickers.radialtimepicker.RadialTimePickerDialogFragment;
import com.mobartisan.workinglunch.R;
import com.mobartisan.workinglunch.bean.AccountRecord;
import com.mobartisan.workinglunch.constants.Constants;
import com.mobartisan.workinglunch.ui.base.BaseFragment;
import com.mobartisan.workinglunch.util.Global;
import com.mobartisan.workinglunch.util.ObjectUtils;
import com.mobartisan.workinglunch.util.SharedPreferencesUtil;
import com.mobartisan.workinglunch.util.ToastUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import rx.Subscriber;

import static com.mobartisan.workinglunch.constants.Constants.FRAG_TAG_DATE_PICKER;
import static com.mobartisan.workinglunch.constants.Constants.FRAG_TAG_TIME_PICKER;
import static com.mobartisan.workinglunch.constants.Constants.issubmit;
import static com.mobartisan.workinglunch.ui.activity.LoginActivity.loge;

/**
 * Created by L on 2017/4/26.
 */

public class RecordFragment extends BaseFragment implements CalendarDatePickerDialogFragment.OnDateSetListener, RadialTimePickerDialogFragment.OnTimeSetListener {

    public static final String TAG = RecordFragment.class.getSimpleName();
    @Bind(R.id.rlt_date)
    RelativeLayout rlt_date;
    @Bind(R.id.rlt_time)
    RelativeLayout rlt_time;
    @Bind(R.id.rlt_type)
    RelativeLayout rlt_type;
    @Bind(R.id.tv_date)
    TextView tv_date;
    @Bind(R.id.tv_time)
    TextView tv_time;
    @Bind(R.id.tv_type)
    TextView tv_type;
    @Bind(R.id.buttonId)
    Button button;
    @Bind(R.id.et_money)
    public EditText et_money;
    String date, time, type, money;
    double moneynomber;
    int typeInt;
    boolean isexist = false;
    Handler handler = new Handler();
    int year1, monthOfYear1, dayOfMonth1, hourOfDay1, minute1;
    boolean isSame = false;
    boolean isSuccess = false;
    int typenumber;


    private static final int DECIMAL_DIGITS = 2;//小数的位数
    private Dialog dilog = null;
    private TextView breakfast, lunch, dinner, other;
    private TextView date2, time2, type2, money2, cancel, confirm, placeholder;
    private LinearLayout determine;
    private RelativeLayout morning, nooning, night, others;
    private ImageView ismorning, isnooning, isnight, isother;
    private View view;
    private static RecordFragment recordFragment;

    public static RecordFragment getInstance() {
        if (recordFragment == null)
            recordFragment = new RecordFragment();
        return recordFragment;
    }

    public void initDialog() {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) (Global.SCREEN_WIDTH * 0.8), ViewGroup.LayoutParams.WRAP_CONTENT);
        dilog = new Dialog(getContext(), R.style.mystyle);
        view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_common, null);
        dilog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        // view.setLayoutParams(params);
        dilog.setCanceledOnTouchOutside(true);
        dilog.setContentView(view);
        Window dialogWindow = dilog.getWindow();
        WindowManager m = getActivity().getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高度
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.height = ViewGroup.LayoutParams.WRAP_CONTENT; // 高度设置为屏幕的0.6，根据实际情况调整
        p.width = (int) (d.getWidth() * 0.7); // 宽度设置为屏幕的0.65，根据实际情况调整
        dialogWindow.setAttributes(p);
        breakfast = (TextView) view.findViewById(R.id.commondialog_breakfast);
        lunch = (TextView) view.findViewById(R.id.commondialog_lunch);
        dinner = (TextView) view.findViewById(R.id.commondialog_dinner);
        other = (TextView) view.findViewById(R.id.commondialog_other);
        morning = (RelativeLayout) view.findViewById(R.id.rlt_morning);
        nooning = (RelativeLayout) view.findViewById(R.id.rlt_nooning);
        night = (RelativeLayout) view.findViewById(R.id.rlt_night);
        others = (RelativeLayout) view.findViewById(R.id.rlt_other);
        ismorning = (ImageView) view.findViewById(R.id.image_isChicked_morning);
        isnooning = (ImageView) view.findViewById(R.id.image_isChicked_nooning);
        isnight = (ImageView) view.findViewById(R.id.image_isChicked_night);
        isother = (ImageView) view.findViewById(R.id.image_isChicked_other);
    }

    public void initDialog2() {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) (Global.SCREEN_WIDTH * 0.8), ViewGroup.LayoutParams.WRAP_CONTENT);
        dilog = new Dialog(getContext(), R.style.mystyle);
        view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_common, null);
        dilog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        // view.setLayoutParams(params);
        dilog.setCanceledOnTouchOutside(true);
        dilog.setContentView(view);
        Window dialogWindow = dilog.getWindow();
        WindowManager m = getActivity().getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高度
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.height = ViewGroup.LayoutParams.WRAP_CONTENT; // 高度设置为屏幕的0.6，根据实际情况调整
        p.width = (int) (d.getWidth() * 0.7); // 宽度设置为屏幕的0.65，根据实际情况调整
        dialogWindow.setAttributes(p);

        breakfast = (TextView) view.findViewById(R.id.commondialog_breakfast);
        lunch = (TextView) view.findViewById(R.id.commondialog_lunch);
        dinner = (TextView) view.findViewById(R.id.commondialog_dinner);
        other = (TextView) view.findViewById(R.id.commondialog_other);
        placeholder = (TextView) view.findViewById(R.id.tv_placeholder);
        date2 = (TextView) view.findViewById(R.id.tv_date);
        time2 = (TextView) view.findViewById(R.id.tv_time);
        type2 = (TextView) view.findViewById(R.id.tv_type);
        money2 = (TextView) view.findViewById(R.id.tv_money);
        cancel = (TextView) view.findViewById(R.id.commondialog_leftbut);
        confirm = (TextView) view.findViewById(R.id.commondialog_rightbut);
        determine = (LinearLayout) view.findViewById(R.id.lin_determine);
    }

    protected void showDilog(View.OnClickListener listener) {
        dilog = null;
        if (dilog == null)
            initDialog();
        this.morning.setOnClickListener(listener);
        this.nooning.setOnClickListener(listener);
        this.night.setOnClickListener(listener);
        this.others.setOnClickListener(listener);
        typenumber = SharedPreferencesUtil.getInstance().getIntValue("type");
        showimage(typenumber);
        dilog.show();
    }

    private void showimage(int typenumber) {
        switch (typenumber){
            case 0:
                ismorning.setVisibility(View.VISIBLE);
                break;
            case 1:
                isnooning.setVisibility(View.VISIBLE);
                break;
            case 2:
                isnight.setVisibility(View.VISIBLE);
                break;
            case 3:
                isother.setVisibility(View.VISIBLE);
                break;
        }
    }

    protected void showSubmitDilog(String date, String time, String type, String money, View.OnClickListener listener) {
        dilog = null;
        if (dilog == null)
            initDialog2();
        determine.setVisibility(View.VISIBLE);
        date2.setVisibility(View.VISIBLE);
        time2.setVisibility(View.VISIBLE);
        type2.setVisibility(View.VISIBLE);
        money2.setVisibility(View.VISIBLE);
        placeholder.setVisibility(View.VISIBLE);
        breakfast.setText("日期:");
        lunch.setText("时间:");
        dinner.setText("类型:");
        other.setText("金额:");
        date2.setText(date);
        time2.setText(time);
        type2.setText(type);
        money2.setText(money);
        cancel.setText("取消");
        confirm.setText("确定");
        cancel.setOnClickListener(listener);
        confirm.setOnClickListener(listener);
        dilog.show();
    }


    public void dismissDilog() {
        if (dilog != null && dilog.isShowing())
            dilog.dismiss();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_record;
    }

    @Override
    protected void initView(View view) {
        TextView title = (TextView) view.findViewById(R.id.common_title_title);
        title.setText("提交");
        //SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm");
        defshow();
        // tv_type.setText(type);
    }

    private void defshow() {
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间  
        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat formatterdate1 = new SimpleDateFormat("yyyy");
        SimpleDateFormat formatterdate2 = new SimpleDateFormat("MM");
        SimpleDateFormat formatterdate3 = new SimpleDateFormat("dd");

        SimpleDateFormat formatter2 = new SimpleDateFormat("HH");
        SimpleDateFormat formatter3 = new SimpleDateFormat("mm");
        date = formatter1.format(curDate);
        time = formatter2.format(curDate) + ":" + formatter3.format(curDate);

        isSuccess = true;
        tv_date.setText(date);
        tv_time.setText(time);
        et_money.setText("");
        setPoint(et_money);
        String hour = formatter2.format(curDate);
        String minutes = formatter3.format(curDate);
        String year = formatterdate1.format(curDate);
        String monthOfYear = formatterdate2.format(curDate);
        String dayOfMonth = formatterdate3.format(curDate);
        hourOfDay1 = Integer.valueOf(hour);
        minute1 = Integer.valueOf(minutes);
        year1 = Integer.valueOf(year);
        monthOfYear1 = Integer.valueOf(monthOfYear);
        dayOfMonth1 = Integer.valueOf(dayOfMonth);
        if (date.equals(joint2(year1, monthOfYear1-1, dayOfMonth1))){
            isSame = true;
        }
        if ((5 <= hourOfDay1 && hourOfDay1 < 9) || (hourOfDay1 == 9 && minute1 <= 30)) {
            type = "早上";
            tv_type.setText(type);
            SharedPreferencesUtil.getInstance().setIntValue("type", 0);
        } else if ((11 <= hourOfDay1 && hourOfDay1 < 14)|| (hourOfDay1 == 14 && minute1 == 0)) {
            type = "中午";
            tv_type.setText(type);
            SharedPreferencesUtil.getInstance().setIntValue("type", 1);
        } else if ((17 <= hourOfDay1 && hourOfDay1 < 20) || (hourOfDay1 == 20 && minute1 <= 30)) {
            type = "晚上";
            tv_type.setText(type);
            SharedPreferencesUtil.getInstance().setIntValue("type", 2);
        } else {
            type = "其它";
            tv_type.setText(type);
            SharedPreferencesUtil.getInstance().setIntValue("type", 3);
        }
    }

    @OnClick({R.id.rlt_date, R.id.rlt_time, R.id.rlt_type, R.id.buttonId})
    public void onclick(View view) {
        switch (view.getId()) {
            case R.id.rlt_date:
                CalendarDatePickerDialogFragment cdp = new CalendarDatePickerDialogFragment()
                        .setOnDateSetListener(this);
                cdp.show(getFragmentManager(), FRAG_TAG_DATE_PICKER);
                break;
            case R.id.rlt_time:
                RadialTimePickerDialogFragment rtpd = new RadialTimePickerDialogFragment()
                        .setOnTimeSetListener(this);
                rtpd.show(getFragmentManager(), FRAG_TAG_TIME_PICKER);
                break;
            case R.id.rlt_type:
                showDilog(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (v.getId()) {
                            case R.id.rlt_morning:
                                type = breakfast.getText().toString();
                                tv_type.setText(type);
                                ismorning.setVisibility(View.VISIBLE);
                                SharedPreferencesUtil.getInstance().setIntValue("type", 0);
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        dismissDilog();
                                    }
                                }, 100);

                                break;
                            case R.id.rlt_nooning:
                                type = lunch.getText().toString();
                                tv_type.setText(type);
                                isnooning.setVisibility(View.VISIBLE);
                                SharedPreferencesUtil.getInstance().setIntValue("type", 1);
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        dismissDilog();
                                    }
                                }, 100);
                                break;
                            case R.id.rlt_night:
                                type = dinner.getText().toString();
                                tv_type.setText(type);
                                isnight.setVisibility(View.VISIBLE);
                                SharedPreferencesUtil.getInstance().setIntValue("type", 2);
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        dismissDilog();
                                    }
                                }, 100);
                                break;
                            case R.id.rlt_other:
                                type = other.getText().toString();
                                tv_type.setText(type);
                                isother.setVisibility(View.VISIBLE);
                                SharedPreferencesUtil.getInstance().setIntValue("type", 3);
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        dismissDilog();
                                    }
                                }, 100);
                                break;
                        }
                    }
                });
                break;
            case R.id.buttonId:
                money = et_money.getText().toString();
                if (!ObjectUtils.isStringNotEmpty(money)) {
                    ToastUtils.showShort("请输入金额");
                    return;
                }
                moneynomber = Double.parseDouble(money);
                if (!ObjectUtils.isStringNotEmpty(date) || !ObjectUtils.isStringNotEmpty(time) || !ObjectUtils.isStringNotEmpty(type) || !ObjectUtils.isStringNotEmpty(money)) {
                    ToastUtils.showShort("请正确填入信息");
                } else {
                    if (moneynomber > 1000) {
                        ToastUtils.showShort("输入金额不可超过1000，请重新输入");
                        et_money.setText("");
                    } else if (moneynomber <= 0) {
                        ToastUtils.showShort("输入金额需要大于0，请重新输入");
                        et_money.setText("");
                    } else {
                        typeInt = SharedPreferencesUtil.getInstance().getIntValue("type");
                        queryObjects();
                    }
                }
                break;
        }
    }

    private void insertObject(String userId, Integer typeNumber) {

        issubmit = true;
        AccountRecord accountRecord = new AccountRecord();
        accountRecord.setUserId(userId);
        accountRecord.setDateStamp(date);
        accountRecord.setTimeStamp(time);
        accountRecord.setType(typeNumber);
        accountRecord.setMoney(moneynomber);
        accountRecord.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {

                    ToastUtils.showShort("提交完成");
                    ListFragment.getFragmetntA().handler.sendEmptyMessage(0);
                    isSame = true;
                    isSuccess = true;
                    defshow();
                } else {
                    ToastUtils.showShort("提交失败");
                    loge(e,TAG);
                }
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onDateSet(CalendarDatePickerDialogFragment dialog, int year, int monthOfYear, int dayOfMonth) {

        if (year1 > year) {
            isSame = false;
            showdate(year, monthOfYear, dayOfMonth);
        } else if (year1 == year) {
            if (monthOfYear1 > (monthOfYear + 1)) {
                isSame = false;
                showdate(year, monthOfYear, dayOfMonth);
            } else if (monthOfYear1 == (monthOfYear + 1)) {
                if (dayOfMonth1 > dayOfMonth) {
                    isSame = false;
                    showdate(year, monthOfYear, dayOfMonth);
                } else if (dayOfMonth1 == dayOfMonth) {
                    if (!isSuccess){
                        ToastUtils.showShort("不可输入未来时间");
                    }else {
                        isSame = true;
                        showdate(year, monthOfYear, dayOfMonth);
                    }
                } else {
                    ToastUtils.showShort("不可输入未来时间");
                }
            } else {
                ToastUtils.showShort("不可输入未来时间");
            }
        } else {
            ToastUtils.showShort("不可输入未来时间");
        }

    }

    private void showdate(int year, int monthOfYear, int dayOfMonth) {
        String month = "" + (monthOfYear + 1), day = "" + dayOfMonth;

        if (monthOfYear < 10) {
            month = "0" + (monthOfYear + 1);
        }
        if (dayOfMonth < 10) {
            day = "0" + dayOfMonth;
        }
        date = year + "-" + month + "-" + day;
        tv_date.setText(date);
    }

    @Override
    public void onTimeSet(RadialTimePickerDialogFragment dialog, int hourOfDay, int minute) {

        if (!isSame) {
            if (hourOfDay1 < hourOfDay){
                isSuccess=false;
            }else if (hourOfDay1==hourOfDay&&minute1 < (minute - 5)){
                isSuccess=false;
            }else if (hourOfDay1==hourOfDay&&minute1 >= (minute - 5)){
                isSuccess=true;
            }else if (hourOfDay1>hourOfDay){
                isSuccess=true;
            }
            showtime(hourOfDay, minute);
        } else {
            if (hourOfDay1 > hourOfDay) {
                isSuccess=true;
                showtime(hourOfDay, minute);
            } else if (hourOfDay1 == hourOfDay) {
                if (minute1 >= (minute - 5)) {
                    isSuccess=true;
                    showtime(hourOfDay, minute);
                } else {
                    ToastUtils.showShort("不可输入未来时间");
                }

            } else {
                ToastUtils.showShort("不可输入未来时间");
            }
        }
    }

    private void showtime(int hourOfDay, int minute) {

        if (minute < 10 && hourOfDay < 10) {
            time = "0" + hourOfDay + ":0" + minute;
        } else if (hourOfDay >= 10 && minute < 10) {
            time = hourOfDay + ":0" + minute;
        } else if (hourOfDay < 10 && minute >= 10) {
            time = "0"+hourOfDay + ":" + minute;
        } else {
            time = hourOfDay + ":" + minute;
        }
        tv_time.setText(time);
        if ((5 <= hourOfDay && hourOfDay < 9) || (hourOfDay == 9 && minute <= 30)) {
            type = "早上";
            tv_type.setText(type);
            SharedPreferencesUtil.getInstance().setIntValue("type", 0);
        } else if ((11 <= hourOfDay && hourOfDay < 14) || (hourOfDay == 14 && minute == 0)) {
            type = "中午";
            tv_type.setText(type);
            SharedPreferencesUtil.getInstance().setIntValue("type", 1);
        } else if ((17 <= hourOfDay && hourOfDay < 20) || (hourOfDay == 20 && minute <= 30)) {
            type = "晚上";
            tv_type.setText(type);
            SharedPreferencesUtil.getInstance().setIntValue("type", 2);
        } else {
            type = "其它";
            tv_type.setText(type);
            SharedPreferencesUtil.getInstance().setIntValue("type", 3);
        }
    }

    public void queryObjects() {
        String userId = SharedPreferencesUtil.getInstance().getStringValue("username");
        final BmobQuery<AccountRecord> bmobQuery = new BmobQuery<AccountRecord>();
        bmobQuery.addWhereEqualTo("userId", userId);
        bmobQuery.addWhereEqualTo("dateStamp", date);

        //bmobQuery.setLimit(2);
//        bmobQuery.order("createdAt");
//        //先判断是否有缓存
//        boolean isCache = bmobQuery.hasCachedResult(AccountRecord.class);
//        if(isCache){
//            bmobQuery.setCachePolicy(BmobQuery.CachePolicy.CACHE_ELSE_NETWORK);	// 先从缓存取数据，如果没有的话，再从网络取。
//        }else{
//            bmobQuery.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);	// 如果没有缓存的话，则先从网络中取
//        }
//		observable形式
        bmobQuery.findObjectsObservable(AccountRecord.class)
                .subscribe(new Subscriber<List<AccountRecord>>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (((BmobException)e).getErrorCode()== Constants.Network_Error_Code){
                            ToastUtils.showShort("提交失败,请检查您的网络");
                        }else if (((BmobException)e).getErrorCode()== Constants.Network_Timeout_Code) {
                            ToastUtils.showShort("网络超时");
                        }
                            loge(e,TAG);
                    }

                    @Override
                    public void onNext(List<AccountRecord> persons) {
                        //log("查询成功：共"+persons.size()+"条数据。");
                        //ToastUtils.showShort("查询成功：共" + persons.size() + "条数据。");
                        for (AccountRecord accountRecord : persons) {
                            if (accountRecord.getType() == typeInt) {
                                isexist = true;
                            }
                        }
                        if (isexist) {
                            ToastUtils.showShort("此类型的记录已经存在");
                            isexist = false;
                        } else {
                            showSubmitDilog(date, time, type, money, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    switch (v.getId()) {
                                        case R.id.commondialog_leftbut:
                                            dismissDilog();
                                            break;
                                        case R.id.commondialog_rightbut:
                                            String userId = SharedPreferencesUtil.getInstance().getStringValue("username");
                                            Integer typeNumber = SharedPreferencesUtil.getInstance().getIntValue("type");
                                            insertObject(userId, typeNumber);
                                            dismissDilog();
                                            break;
                                    }
                                }
                            });

                        }

                    }
                });
//		bmobQuery.findObjects(new FindListener<Person>() {
//
//			@Override
//			public void done(List<Person> object, BmobException e) {
//				if(e==null){
//					toast("查询成功：共"+object.size()+"条数据。");
//					for (Person person : object) {
//						Log.d(TAG, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ");
//						Log.d(TAG, "ObjectId = "+person.getObjectId());
//						Log.d(TAG, "Name = "+person.getName());
//						Log.d(TAG, "Age = "+person.getAge());
//						Log.d(TAG, "Address = "+person.getAddress());
//						Log.d(TAG, "Gender = "+person.isGender());
//						Log.d(TAG, "CreatedAt = "+person.getCreatedAt());
//						Log.d(TAG, "UpdatedAt = "+person.getUpdatedAt());
//					}
//				}else{
//					loge(e);
//				}
//			}
//		});
    }
    private String joint2(int year, int monthOfYear, int dayOfMonth) {
        String month = "" + (monthOfYear + 1), day = "" + dayOfMonth;
        String testdate;
        if (monthOfYear < 10) {
            month = "0" + (monthOfYear + 1);
        }
        if (dayOfMonth < 10) {
            day = "0" + dayOfMonth;
        }
        testdate = year + "-" + month + "-" + day;
        return testdate;
    }
    public static void setPoint(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > DECIMAL_DIGITS) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + DECIMAL_DIGITS+1);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }
                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,int after) {
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }
}
